package isd.com.smarthome.udp;

import isd.com.smarthome.util.SmartHomeConstant;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.util.Log;

public class UDPServer implements SmartHomeConstant {

	public void SmartHomeService() {
		 new Thread(runner).start(); 
	}
	private static final int MAX_UDP_DATAGRAM_LEN = 1500;
    Runnable runner = new Runnable() {      
        @Override
        public void run() {
            while(true){    
            	String Values;
            	byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN];
            	DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
            	DatagramSocket ds = null;
            	try {
        			ds = new DatagramSocket(INPUTPORT);
        			//disable timeout for testing
        			//ds.setSoTimeout(100000);
        			ds.receive(dp);
        			Values = new String(lMsg, 0, dp.getLength());
        			Log.i("UDP packet received", Values);
        			// luu data in database 
        			 

                } catch (SocketException e) {
        			e.printStackTrace();
        		}catch (UnknownHostException e) {
        			e.printStackTrace();
        		} catch (IOException e) {
        			e.printStackTrace();
        		} catch (Exception e) {
        			e.printStackTrace();
        		} finally {
        			if (ds != null) {
        				ds.close();
        			}
        		}
            }

        }
    };
	/// send to Service 
//	 private static final int UDP_SERVER_PORT = 11111;
	    public void SmartHomeClient(String values)  {
	    	DatagramSocket ds = null;
	    	try {
				ds = new DatagramSocket();
				InetAddress serverAddr = InetAddress.getByName(SERVER_HOST);
				DatagramPacket dp;
				dp = new DatagramPacket(values.getBytes(), values.length(), serverAddr, SENDPORT);
				ds.send(dp);
			} catch (SocketException e) {
				e.printStackTrace();
			}catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				Log.i("loi EX",e.toString());
				e.printStackTrace();
			} finally {
				if (ds != null) {
					ds.close();
				}
			}
	    }

}
